package com.cms.thread.impl;

import com.aliyun.mns.common.ServiceException;
import com.cms.ClassScaner;
import com.cms.CommonAttribute;
import com.cms.entity.*;
import com.cms.enums.VIPEnums;
import com.cms.thread.IBuyThread;
import com.cms.util.LockInfo;
import com.jfinal.log.Log;

import java.math.BigDecimal;

/**
 * @author ：chenxf
 * @date ：Created in 2019/8/5 14:59
 * @description：购买线程
 * @modified By：
 * @version: $
 */
public class BuyThreadImpl  {
    private static final com.jfinal.log.Log log = Log.getLog(BuyThreadImpl.class);
    private Order order;

   public BuyThreadImpl(Order order){
       this.order=order;
   }

    public void completeBuy(Order order) {
        //更新用户信息
        Member member=new Member().updateMember(order,order.getMemberId());

        //上级信息更新+发放级差奖+业绩奖
        if(member.getParentId()!=null){
            completeParent(order,member.getParentId(), member.getVipLevel(),member.getMobile(),0);
        }


    }

    public void completeParent(Order order,Long parentId,int buyLevel,String name,int level){
//       if(buyLevel==0){
//           buyLevel=1;
//       }

        //更新用户信息
        Member member=new Member().updateMember(order,parentId);
        if(buyLevel>=6&& level>=3){
            log.debug("大于VIP6 层级大于 3 业绩奖和级差奖不发放");
        }else{
            for(OrderItem item:order.getOrderItems()){
                Product product= item.getProduct();
                if(level<3){
                    //发放业绩奖
                    BigDecimal yjj=product.getMemberPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
                    new Money().addYjj(parentId,yjj,String.format(CommonAttribute.MONEY_LOG,name,product.getName(),yjj.toString(),"业绩奖"));
                }

                //发放级差奖
                if(buyLevel<member.getVipLevel()){
                    BigDecimal jcj=product.getLevelPrice().multiply(BigDecimal.valueOf(item.getQuantity())).multiply(BigDecimal.valueOf(member.getVipLevel()-buyLevel));
                    new Money().addJcj(parentId,jcj,String.format(CommonAttribute.MONEY_LOG,name,product.getName(),jcj.toString(),"级差奖"));
                }
            }
        }

        level++;
        //上级信息更新+发放级差奖+业绩奖
        if(member.getParentId()!=null){
            completeParent(order,member.getParentId(), member.getVipLevel(),name,level);
        }else {
            log.debug("无上级，任务结束");
        }

    }



    public void run() {
        log.debug("线程开始");
        completeBuy(order);
        log.debug("线程结束");
    }
}
